package org.TheSubject;

import java.util.*;

/**给你一个包含 n 个整数的数组 nums，判断 nums 中是否存在三个元素 a，b，c ，使得 a + b + c = 0 ？请你找出所有和为 0 且不重复的三元组。

 注意：答案中不可以包含重复的三元组。
 输入：nums = [-1,0,1,2,-1,-4]
 输出：[[-1,-1,2],[-1,0,1]]
 */
public class Solution15OfHot {
    public static void main(String[] args) {
        Solution15OfHot solution15OfHot = new Solution15OfHot();
        int[] x={-1,0,1,2,-1,-4};
        System.out.println(solution15OfHot.threeSum(x));
    }

    static public final int wantSum=0;
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> ans = new ArrayList<>();
        int size=nums.length;
        int endIndex=size-1;
        if (nums == null || nums.length < 3)
            return ans;
        Arrays.sort(nums);
        for(int i=0;i<size-2;i++){
            int nowNum=nums[i];
            if (nowNum>0){
                break;
            }
            if(i!=0&&nowNum==nums[i-1]){
                continue;
            }
            int target=wantSum-nowNum;
            int left=i+1,right=size-1;
            while (left<right){
                int nowSum=nums[left]+nums[right];
                if (nowSum==target){
                    ans.add(new ArrayList<>(Arrays.asList(nowNum,nums[left],nums[right])));
                    left++;right--;
                    while (left<right&&nums[left]==nums[left-1]) left++;
                    while (left<right&&nums[right]==nums[right+1]) right--;
                }else if (nowSum<target){
                    left++;
                }else if(nowSum>target){
                    right--;
                }
            }
        }
        return ans;
    }
}
